package com.shiyi.quartz;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.shiyi.common.RedisConstants;
import com.shiyi.entity.Article;
import com.shiyi.entity.Tags;
import com.shiyi.service.ArticleService;
import com.shiyi.service.CloudOssService;
import com.shiyi.service.RedisService;
import com.shiyi.service.TagsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;

import static com.shiyi.common.RedisConstants.*;

/**
 * @author blue
 * @date 2021/12/8
 * @apiNote 定时任务调度
 */
@Component("blogQuartz")
@Slf4j
@RequiredArgsConstructor
public class BlogQuartz {
    private final RedisService redisService;

    private final ArticleService articleService;

    private final CloudOssService cloudOssService;

    private final TagsService tagsService;


    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() {
        System.out.println("执行无参方法");
    }

    /**
     *  redis心跳,解决总是存在Command timed out after 3 second(s)的问题
     * @author blue
     * @date: 2021/8/18 17:58
     */
    public void redisTimer(){
        redisService.redisTimer();
    }

    /**
     *  自动更新阅读数，每天凌晨四点更新数据
     * @author blue
     * @date: 2021/8/18 17:58
     */
    public void updateReadQuantity(){
        // 获取带阅读量的前缀key集合
        List<Article> articles = new ArrayList<>();
        Map<String, Object> map = redisService.getCacheMap(ARTICLE_READING);
        // 取出所有数据更新到数据库
        for (Map.Entry<String, Object> stringEntry : map.entrySet()) {
            String id = stringEntry.getKey();
            List<String> list = (List<String>) stringEntry.getValue();
            Article article = Article.builder()
                    .id(Long.parseLong(id)).quantity(list.size())
                    .build();
            articles.add(article);
        }
        articleService.updateBatchById(articles);
    }

    /**
     * 删除七牛云的垃圾图片
     *
     */
    public void removeQiNiuImg(){
//        Set<String> imgArrays = redisService.diff(RedisConstants.IMG_UPLOAD_ALL, RedisConstants.IMG_UPLOAD_MYSQL);
        Set<String> imgArrays = redisService.diff(RedisConstants.ALL_IMG, RedisConstants.APPLY_IMG);
//        String[] keys = imgArrays.toArray(new String[0]);

        String[] keys = imgArrays.stream().map(e -> {
            return e.replace(IMG_HEADER, "");
        }).toArray(String[] :: new);
        cloudOssService.delBatchFile(keys);
    }

    /**
     * 删除7天前redis存的上传图片信息
     */
    public void removeRedisImgSevenDayAge(){
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        ArrayList<Object> delList = new ArrayList<>();
        Set<Object> allImg = redisService.getCacheSet(ALL_IMG);
        LocalDate localDate = now.minusDays(7);// 7天前
        for (Object o : allImg) {
            String string = o.toString();
            String replace = string.replace(IMG_HEADER, "");
            String time = replace.split("_")[0];
            LocalDate parse = LocalDate.parse(time, formatter);
            // 小于七天
            if (parse.isBefore(localDate)) {
                delList.add(o.toString());
            }
        }
        if (!delList.isEmpty()){
            Long l = redisService.sRemove(ALL_IMG, delList.toArray());
        }

        ArrayList<String> delList1 = new ArrayList<>();
        Set<Object> applyImg = redisService.getCacheSet(APPLY_IMG);
        for (Object o : applyImg) {
            String string = o.toString();
            String replace = string.replace(IMG_HEADER, "");
            String time = replace.split("_")[0];
            LocalDate parse = LocalDate.parse(time, formatter);
            // 小于七天
            if (parse.isBefore(localDate)) {
                delList1.add(o.toString());
            }
        }
        if (!delList1.isEmpty()){
            Long l = redisService.sRemove(APPLY_IMG, delList1.toArray());
            System.out.println(l);
        }

    }

    /**
     * 删除redis当天验证码通过的ip
     *
     */
    public void removeCodePassInIp(){
        redisService.deleteObject(RedisConstants.CHECK_CODE_IP);
    }

    /**
     * 每天定时修改标签的点击量
     *
     */
    public void updateTagsClickVolume(){
        Map<String, Object> map = redisService.getCacheMap(TAG_CLICK_VOLUME);
        List<Tags> tagsList = new ArrayList<>();
        for (Map.Entry<String, Object> stringEntry : map.entrySet()) {
            String id = stringEntry.getKey();
            Integer value = (Integer) stringEntry.getValue();
            Tags tags = new Tags(Long.parseLong(id),value);
            tagsList.add(tags);
        }
        tagsService.updateBatchById(tagsList);
    }




    /**
     * 测试 demo
     *
     */
    /**
     * 测试 demo
     *
     */
    /**
     * 测试 demo
     *
     */
    public void testDemo(){
        LocalDateTime now = LocalDateTime.now();
        log.info("当前时间：{},当前线程：{}", now, Thread.currentThread().getId());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("任务完成。" +  now + "--"+Thread.currentThread().getId());
    }
}
